package com.galen.manual.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.galen.manual.common.Result;
import com.galen.manual.dto.SettlementCreateDTO;
import com.galen.manual.dto.SettlementQueryDTO;
import com.galen.manual.service.SettlementService;
import com.galen.manual.vo.SettlementListVO;
import com.galen.manual.vo.SettlementVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.time.LocalDateTime;
import java.util.List;

@Tag(name = "结算管理", description = "结算相关接口")
@RestController
@RequestMapping("/settlements")
@RequiredArgsConstructor
public class SettlementController {

    private final SettlementService settlementService;

    @Operation(summary = "获取结算单列表", description = "分页获取结算单列表（管理员用）")
    @GetMapping
    public Result<Page<SettlementListVO>> getSettlementPage(
            @Parameter(description = "查询条件") SettlementQueryDTO queryDTO) {
        Page<SettlementListVO> settlements = settlementService.getSettlementPage(queryDTO);
        return Result.success(settlements);
    }

    @Operation(summary = "获取用户结算单列表", description = "分页获取当前用户的结算单列表")
    @GetMapping("/my")
    public Result<Page<SettlementListVO>> getUserSettlementPage(
            @Parameter(description = "查询条件") SettlementQueryDTO queryDTO,
            @AuthenticationPrincipal UserDetails userDetails) {
        // 从JWT中获取用户ID，这里暂时写死，实际应该从JWT中解析
        Long userId = 1L; // TODO: 从JWT中获取用户ID
        Page<SettlementListVO> settlements = settlementService.getUserSettlementPage(userId, queryDTO);
        return Result.success(settlements);
    }

    @Operation(summary = "获取结算单详情", description = "根据ID获取结算单详细信息")
    @GetMapping("/{id}")
    public Result<SettlementVO> getSettlementDetail(
            @Parameter(description = "结算单ID", required = true) @PathVariable Long id) {
        SettlementVO settlement = settlementService.getSettlementDetail(id);
        return Result.success(settlement);
    }

    @Operation(summary = "创建结算单", description = "创建新的结算单（管理员用）")
    @PostMapping
    public Result<Long> createSettlement(
            @Parameter(description = "结算单信息", required = true) @Valid @RequestBody SettlementCreateDTO createDTO) {
        Long settlementId = settlementService.createSettlement(createDTO);
        return Result.success("结算单创建成功", settlementId);
    }

    @Operation(summary = "自动生成结算单", description = "根据用户完成的任务自动生成结算单")
    @PostMapping("/generate")
    public Result<Long> generateSettlement(
            @Parameter(description = "用户ID", required = true) @RequestParam Long userId,
            @Parameter(description = "开始时间", required = true) @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime startTime,
            @Parameter(description = "结束时间", required = true) @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endTime) {
        Long settlementId = settlementService.generateSettlement(userId, startTime, endTime);
        return Result.success("结算单生成成功", settlementId);
    }

    @Operation(summary = "确认结算单", description = "确认结算单（用户确认）")
    @PutMapping("/{id}/confirm")
    public Result<Void> confirmSettlement(
            @Parameter(description = "结算单ID", required = true) @PathVariable Long id) {
        settlementService.confirmSettlement(id);
        return Result.success("结算单确认成功");
    }

    @Operation(summary = "支付结算单", description = "支付结算单（管理员用）")
    @PutMapping("/{id}/pay")
    public Result<Void> paySettlement(
            @Parameter(description = "结算单ID", required = true) @PathVariable Long id,
            @Parameter(description = "支付方式", required = true) @RequestParam String paymentMethod) {
        settlementService.paySettlement(id, paymentMethod);
        return Result.success("结算单支付成功");
    }

    @Operation(summary = "批量更新结算状态", description = "批量更新结算状态（管理员用）")
    @PutMapping("/batch-status")
    public Result<Void> updateSettlementStatusBatch(
            @Parameter(description = "结算单ID列表", required = true) @RequestBody List<Long> settlementIds,
            @Parameter(description = "结算状态", required = true) @RequestParam Integer status) {
        settlementService.updateSettlementStatusBatch(settlementIds, status);
        return Result.success("批量更新成功");
    }

    @Operation(summary = "获取用户结算总金额", description = "获取用户的累计结算总金额")
    @GetMapping("/my/total")
    public Result<java.math.BigDecimal> getUserTotalSettlementAmount(
            @AuthenticationPrincipal UserDetails userDetails) {
        // 从JWT中获取用户ID，这里暂时写死，实际应该从JWT中解析
        Long userId = 1L; // TODO: 从JWT中获取用户ID
        java.math.BigDecimal totalAmount = settlementService.getUserTotalSettlementAmount(userId);
        return Result.success(totalAmount != null ? totalAmount : java.math.BigDecimal.ZERO);
    }
}